package com.example.config;

import com.example.result.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 */
//如果存在@RestController和@Controller注解就接收
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 重复异常处理方法
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public JsonResult exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getMessage());

        if(ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return new JsonResult(0,msg);
        }

        return new JsonResult(0,"未知错误");
    }

    /**
     * 自定义异常处理方法
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public JsonResult exceptionHandler(CustomException ex){
        log.error(ex.getMessage());

        return new JsonResult(0,ex.getMessage());
    }
    /**
     * 运行时异常处理方法
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    public JsonResult exceptionHandler(RuntimeException ex){
        log.error(ex.getMessage());

        return new JsonResult(0,ex.getMessage());
    }
    /**
     * 上传文件服务器超标时
     * @return
     */
    @ExceptionHandler(FileSizeLimitExceededException.class)
    public JsonResult exceptionHandler(FileSizeLimitExceededException ex){
        log.error(ex.getMessage());

        return new JsonResult(0,"您的文件过大上传失败!");
    }
}